package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"

	"smp/mlib"
	"smp/mp"
)

var AllowType = map[string]string{"MP3": "MP3", "WAV": "WAV"}

var lib *mlib.MusicManager
var id int = 1
var ctrl, signal chan int

func handleLibCommands(args []string) {
	switch args[1] {
	case "list":
		for i := 0; i < lib.Len(); i++ {
			e, _ := lib.Get(i)
			fmt.Println(i+1, ":", e.Name, e.Artist, e.Source, e.Type)
		}

	case "add":
		if len(args) == 6 {
			if _, ok := AllowType[args[5]]; ok {
				id++
				lib.Add(&mlib.MusicEntry{strconv.Itoa(id),
					args[2], args[3], args[4], args[5]})
			} else {
				allowType := []string{}
				for k, _ := range AllowType {
					allowType = append(allowType, k)
				}
				fmt.Println("USAGE: type must in [", strings.Join(allowType, ", "), "]")
			}

		} else {
			fmt.Println("USAGE: lib add <name><artist><source><type>")
		}

	case "remove":
		if len(args) == 3 {
			index, _ := strconv.Atoi(args[2])
			lib.Remove(index)
		} else {
			fmt.Println("USAGE: lib remove <name>")
		}

	default:
		fmt.Println("Unrecognized lib command:", args[1])
	}
}

func handlePlayCommand(args []string) {
	if len(args) != 2 {
		fmt.Println("USAGE: play <name>")
		return
	}

	e := lib.Find(args[1])
	if e == nil {
		fmt.Println("The music", args[1], "does not exist.")
		return
	}

	mp.Play(e.Source, e.Type)
}

func main() {

	fmt.Println(`
Enter followint command to control the player:
lib list -- View the existing music lib
lib add <name><artist><source><type> --Add a music to the music lib
lib remove <name> -- Remove the specified music from the lib
play <name> -- Play the specified music`)

	lib = mlib.NewMusicManager()

	r := bufio.NewReader(os.Stdin)

	for {
		fmt.Print("Enter command-> ")
		rawLine, _, _ := r.ReadLine()
		line := string(rawLine)

		if line == "q" || line == "e" {
			break
		}

		args := strings.Split(line, " ")

		fmt.Println(args)

		if args[0] == "lib" {
			handleLibCommands(args)
		} else if args[0] == "play" {
			handlePlayCommand(args)
		} else {
			fmt.Println("Unrecognized command:", args[0])
		}
	}
}
